#include <interface.h>

#include <book.h>

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>


void movegen_init();
void eval_init();
void ttable_init();
void stat_init();
void ttable_cleanup();
void stat_print();

/*
 * TODO
 * - command line interface
 * - decorate moves from input text (and check legality)
 * - try to remove the squares field
 * - Add assertions to make_move to verify the legality of moves
 *   (e.g. no king captures)
 */

int main(int argc, char* argv[])
{
  movegen_init();
  eval_init();
  ttable_init();
  stat_init();
  book_load("default.book");  // ignore possible errors
  
  if (argc > 2) {
    printf("Usage:\n %s [OPTIONS...] [SCRIPT]\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  int fd = 0;
  if (argc == 2) {
    fd = open(argv[1], O_RDONLY);
    if (fd < 0) {
      fprintf(stderr, "Failed to open %s\n", argv[1]);
      exit(EXIT_FAILURE);
    }
  }

  interface_t interface;
  interface_init(&interface);
  interface_set_input(&interface, fd);

  interface_main_loop(&interface);

  if (fd != 0)
    close(fd);
  stat_print();
  interface_cleanup(&interface);
  ttable_cleanup();
  
  exit(EXIT_SUCCESS);
}
